//
//  TrainTrackAppDelegate.m
//  TrainTrack
//
//  Created by Jonathan Bunde-Pedersen on 03/10/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "TrainTrackAppDelegate.h"
#import "RootViewController.h"
#import "TTTabViewController.h"
#import "Model.h"
#import "Departure.h"
#import "DepartureWalker.h"
#import "TTDepartureCell.h"
#import "Station.h"

@interface TrainTrackAppDelegate (Private)
- (void) createEditableCopyOfDatabaseIfNeeded;
- (void) initializeDatabase;
@end


@implementation TrainTrackAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize database;
@synthesize tabBarController;
@synthesize model;

NSString *_dbPath;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// initialize -- load icons
	[TTDepartureCell initializeGraphics];
	
	// Database initialization
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	_dbPath = [documentsDirectory stringByAppendingPathComponent:@"ttdb.sql"];
	
	[self createEditableCopyOfDatabaseIfNeeded];
	[self initializeDatabase];
	
	// set database for use in other objects
	self.model = [[Model alloc] init];
	self.model.database = self.database;
	
	[Station setDatabase:self.database];
	
	// Configure and show the window
	
	self.tabBarController = [[TTTabViewController alloc] init];
	
	[window addSubview:[self.tabBarController view]];
	[window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}


// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
	// First, test for existence.
	BOOL success;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"ttdb.sql"];
	success = [fileManager fileExistsAtPath:writableDBPath];
	if (success) return;
	// The writable database does not exist, so copy the default to the appropriate location.
	NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ttdb.sql"];
	success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
	if (!success) {
		NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
}

// Open the database connection and retrieve minimal information for first view
- (void)initializeDatabase {
	
	// Open the database. The database was prepared outside the application.
	if (sqlite3_open([_dbPath UTF8String], &database) == SQLITE_OK) {
		
		NSLog(@"Database is open for business");
		
	} else {
		// Even though the open failed, call close to properly clean up resources.
		sqlite3_close(database);
		NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
		// Additional error handling, as appropriate...
	}
}

-(void) deleteFavStation:(NSString *)station {
	const char *delete_fs_sql = "delete from FavouriteStations where station=?";
	sqlite3_stmt *delete_fs_stm;
	if (sqlite3_prepare_v2(database, delete_fs_sql, -1, &delete_fs_stm, NULL) == SQLITE_OK) {
		// bind
		sqlite3_bind_text(delete_fs_stm, 1, [station UTF8String], -1, SQLITE_TRANSIENT);
		if (sqlite3_step(delete_fs_stm) == SQLITE_DONE) {
			NSLog(@"Deleted station %@", station);
		}
	}
	// "Finalize" the statement - releases the resources associated with the statement.
	sqlite3_finalize(delete_fs_stm);
}

-(void) addFavStation:(NSString *)station {
	const char *add_fs_sql = "insert into FavouriteStations values (?)";
	sqlite3_stmt *add_fs_stm;
	if (sqlite3_prepare_v2(database, add_fs_sql, -1, &add_fs_stm, NULL) == SQLITE_OK) {
		// bind
		sqlite3_bind_text(add_fs_stm, 1, [station UTF8String], -1, SQLITE_TRANSIENT);
		if (sqlite3_step(add_fs_stm) == SQLITE_DONE) {
			NSLog(@"Added fav station %@", station);
		}
	}
	// "Finalize" the statement - releases the resources associated with the statement.
	sqlite3_finalize(add_fs_stm);
}

- (void)dealloc {
	[navigationController release];
	[window release];
	[super dealloc];
}

@end
